package com.verisette.ncos.service.card.bizunit;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.corp.agi.common.exception.ProcessException;
import org.corp.agi.service.bean.ProcessContext;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfWriter;
import com.verisette.ncos.common.ProjectConstant;
import com.verisette.ncos.persistence.domain.MasterCompany;
import com.verisette.ncos.persistence.domain.MasterMember;
import com.verisette.ncos.persistence.domain.MasterTemplate;
import com.verisette.ncos.persistence.domain.MasterUserProfile;
import com.verisette.ncos.web.card.bean.CardCreateBean;

public class CreateMittareCardPreviewByTemplateBU extends CreateMittareCardByTemplateBU {
	protected Logger logger = Logger.getLogger(CreateMittareCardPreviewByTemplateBU.class);
	
	protected void addWatermark(PdfContentByte over){
		//Watermark
		over.saveState();
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0.5f);
        over.setGState(gs1);
		Font FONT = new Font(FontFamily.HELVETICA, S_WATERMARK_FONT_SIZE, Font.BOLD, new GrayColor(0.75f));
    	ColumnText.showTextAligned(over,
        		Element.ALIGN_CENTER, new Phrase(S_WATERMARK_TEXT, FONT),
              110.5f, 50, 20);
    	over.restoreState();
	}

	protected String getUserPDFPathDir(){
		return ProjectConstant.APP_TEMP_PDF_PREVIEW_FOLDER;
	}
	
	@Override
	public void execute(ProcessContext processContext) throws ProcessException {
		if(logger.isInfoEnabled()) logger.info( this.getClass().getSimpleName() + ": execute" );
		
		MasterUserProfile userBean = (MasterUserProfile)processContext.getUserBean();
		CardCreateBean cardCreateBean = (CardCreateBean)processContext.getOriginalRequest().getValueObject();
		String userPDFPathDir = getUserPDFPathDir();
		String fullPDFPathFile = userPDFPathDir + "\\" + cardCreateBean.getOrder().getPdfPath();
		
		Rectangle pagesize = new Rectangle(width, height);
		Document document = new Document(pagesize, 0f, 0f, 0f, 0f);
		PdfWriter writer = null;
		
		File output=null;
		try{
			File dir = new File(userPDFPathDir);
			if(!dir.exists()) dir.mkdirs();
			
			output = new File(fullPDFPathFile);
			writer = PdfWriter.getInstance(document, new FileOutputStream(output));
			FontFactory.register(ProjectConstant.FONT_PSLxKittithada_NORMAL, ProjectConstant.FONT_NAME_PSLxKittithada_NORMAL);
			FontFactory.register(ProjectConstant.FONT_PSLxKittithada_BOLD, ProjectConstant.FONT_NAME_PSLxKittithada_BOLD);
			FontFactory.register(ProjectConstant.FONT_PSLxKittithada_ITALIC, ProjectConstant.FONT_NAME_PSLxKittithada_ITALIC);
			
	        document.open();
	        
	        Image personalPic;
	        Image backgroundPic;
	        float factor=0f;

    		String currentPageLanguage = PRINT_TYPE_FLAG[PRINT_TYPE_FLAG_DEF_IDX];
    		
    		String companyName = "";
    		
	        String name = "";
	        String position = "";
	        String agentCode = "";
	        String dept = "";

    		String officeName = "";
    		String officeAddr = "";
    		String officeAddr2 = "";
    		String officeDirect = "";
    		String officeFax = "";
    		String mobile = "";

	        String agentCodeTitle = AGENT_CODE_TITLE_TH;
    		String mobile_title = MOBILE_TITLE_TH;
    		String tel_title = TELEPHONE_TITLE_SALE_TH;
    		String fax_title = FAX_TITLE_TH;
    		
    		MasterCompany company = userBean.getMasterCompany();
    		MasterTemplate template = cardCreateBean.getOrder().getMasterTemplate();
    		MasterMember member = cardCreateBean.getOrder().getMasterMember();
    		boolean isDone = false;
    		String printTypeName = PRINT_TYPE_FLAG[Integer.valueOf(cardCreateBean.getPrintType())];
        	if(printTypeName.indexOf(currentPageLanguage)>-1){
        		if("th".equals(printTypeName)) isDone=true;
        		if(company!=null){
		        	companyName = company.getCompanyNameTh();
        		}
		        if(cardCreateBean!=null && member!=null){
		        	name = String.format("%s %s", member.getMmbFnameTh(), member.getMmbLnameTh());
		        	position = member.getMmbPositionTh();
		        	agentCode = member.getMmbAgentCode();
		        	dept = member.getMmbDeptTh();
	    			if(StringUtils.isNotBlank(member.getMmbOfficeNameTh())){
	    				officeName = member.getMmbOfficeNameTh();
	    			}
	    			if(StringUtils.isNotBlank(member.getMmbOfficeAddrTh())){
	    				officeAddr = member.getMmbOfficeAddrTh();
	    			}
	    			if(StringUtils.isNotBlank(member.getMmbOfficeAddr2Th())){
	    				officeAddr2 = member.getMmbOfficeAddr2Th();
	    			}
	    			if(StringUtils.isNotBlank(member.getMmbPhone())){
	    				officeDirect = member.getMmbPhone();
        				if(StringUtils.isNotBlank(member.getMmbPhone2())){
        					officeDirect = officeDirect + DELIMITER_PHONE + member.getMmbPhone2();
        				}
	    			}
	    			if(StringUtils.isNotBlank(member.getMmbFax())){
	    				officeFax = member.getMmbFax();
        				if(StringUtils.isNotBlank(member.getMmbFax2())){
        					officeFax = officeFax + DELIMITER_PHONE + member.getMmbFax2();
        				}
	    			}
        			if(StringUtils.isNotBlank(member.getMmbMobile())){
        				mobile = member.getMmbMobile();
        				if(StringUtils.isNotBlank(member.getMmbMobile2())){
        					mobile = mobile + DELIMITER_PHONE + member.getMmbMobile2();
        				}
        			}
		        }
        	}
    		
    		boolean isMmbPictureRequired = (cardCreateBean.getOrder().getMasterTemplate()!=null && MTP_REQUIRED_IMAGE_FLAG.equals(cardCreateBean.getOrder().getMasterTemplate().getMtpImgRequired()));
    		
    		boolean imgRequired =ArrayUtils.contains(TEMPLATE_IMG_REQUIRED, template.getMtpId()); 
    		float noImgRequiredSub = 0f;
	        do{
	        	if(!"".equals(name)){
		        	backgroundPic = Image.getInstance(String.format(ProjectConstant.APP_IMAGES_FOLDER + BG_PATH));
	        		if (backgroundPic.getScaledWidth() > width || backgroundPic.getScaledHeight() > height) {
	        			backgroundPic.scaleToFit(width, height);
	        		}
	        		document.add(backgroundPic);
	        		PdfContentByte over = writer.getDirectContent();
	        		addWatermark(over);
	        		if(imgRequired){
			        	if(isMmbPictureRequired && member!=null && member.getMmbPicturePath()!=null && !"".equals(member.getMmbPicturePath())){
			        		personalPic = Image.getInstance(ProjectConstant.APP_TEMP_IMG_FOLDER + "\\" + member.getMmbPicturePath());
			        		float w=IMG_BOX_WEIGHT, h=IMG_BOX_HEIGHT;
			        		float left=IMG_BOX_LEFT, buttom=IMG_BOX_BUTTOM;
			        		personalPic.scaleToFit(w, h);
			        		personalPic.setAbsolutePosition(left, buttom);
			        		personalPic.setBorder(Image.BOX);
			        		personalPic.setBorderWidth(IMG_BOX_BORDER_WEIGHT);
			        		over.saveState();
			        		over.addImage(personalPic);
			        		over.restoreState();
			        	}
	        		}

	        		Font fontUp = FontFactory.getFont(ProjectConstant.FONT_PSLxText_NORMAL, ProjectConstant.EXPORT_ENCODE_TIS620, BaseFont.EMBEDDED, 15, Font.NORMAL, BaseColor.GREEN);
	        		BaseFont font = fontUp.getBaseFont();
	        		Font fontItalicUp = FontFactory.getFont(ProjectConstant.FONT_PSLxText_ITALIC, ProjectConstant.EXPORT_ENCODE_TIS620, BaseFont.EMBEDDED, 15, Font.NORMAL, BaseColor.GREEN);
	        		BaseFont fontItalic = fontItalicUp.getBaseFont();
	        		Font fontBoldUp = FontFactory.getFont(ProjectConstant.FONT_PSLxText_BOLD, ProjectConstant.EXPORT_ENCODE_TIS620, BaseFont.EMBEDDED, 15, Font.BOLD, BaseColor.GREEN);
	        		BaseFont fontBold = fontBoldUp.getBaseFont();

	        		//draw line
	        		float lineLong = fontBold.getWidthPoint(name, 15);
	        		float positionLongPoint = font.getWidthPoint(position, 11);
	        		float agentCodeLongPoint = font.getWidthPoint(agentCodeTitle + agentCode, 11);
	        		float email1LongPoint = font.getWidthPoint("E-mail : "+member.getMmbEmail(), 10);
	        		float email2LongPoint = font.getWidthPoint(member.getMmbEmail2(), 10);
	        		
	        		if(positionLongPoint > lineLong) {
	        			lineLong = positionLongPoint;
	        		}
	        		if(agentCodeLongPoint > lineLong){
	        			lineLong = agentCodeLongPoint;
	        		}
	        		if(email1LongPoint > lineLong){
	        			lineLong = email1LongPoint;
	        		}
	        		if(email2LongPoint > lineLong){
	        			lineLong = email2LongPoint;
	        		}
	        		
	        		over.setLineWidth(0.5f);
	        		over.setColorStroke(MITTARE_COLOR);
	        		over.moveTo(235+8, 119+noImgRequiredSub+4-5);
	        		over.lineTo(235+8-lineLong, 119+noImgRequiredSub+4-5);
	        		over.stroke();
	        		
	        		over.beginText();
	        		int adjust = 4;
	        		int adjust_w = 8;
	        		over.setFontAndSize(fontBold,15);
	        		over.setColorFill(MITTARE_COLOR);
	        		over.showTextAligned(Element.ALIGN_RIGHT, name, 235+adjust_w, 119+noImgRequiredSub+adjust, 0);
	        		over.setFontAndSize(font, 11);
	        		over.showTextAligned(Element.ALIGN_RIGHT, position, 235+adjust_w, 108+noImgRequiredSub+adjust-5, 0);
	        		over.setFontAndSize(font, 11);
            		over.showTextAligned(Element.ALIGN_RIGHT, agentCodeTitle + agentCode, 235+adjust_w, 97+noImgRequiredSub+adjust-4, 0);
            		over.setFontAndSize(font, 10);
            		if(StringUtils.isNotBlank(member.getMmbEmail())){
            			over.showTextAligned(Element.ALIGN_RIGHT, "E-mail : "+member.getMmbEmail(), 235+adjust_w, 89+noImgRequiredSub+adjust-4, 0);
            		}
	        		if(StringUtils.isNotBlank(member.getMmbEmail2())){
	        			over.showTextAligned(Element.ALIGN_RIGHT, member.getMmbEmail2(), 235+adjust_w, 89+noImgRequiredSub+adjust-12, 0);
	        		}
	        		
	        		float part2start = 90;
	        		
	        		//buttom up
	        		float buttomLine = 12;
	        		float lineSpace = 7;
	        		buttomLine+=lineSpace+1;
	        		if(StringUtils.isBlank(officeAddr2)){
	        			lineSpace = 8;
	        			buttomLine = buttomLine-1;
	        		}
	        		over.setFontAndSize(font, 9);
	        		over.showTextAligned(Element.ALIGN_LEFT, MITTARE_CC, 17.5f, buttomLine, 0);
	        		System.out.println(buttomLine);
	        		if(StringUtils.isNotBlank(mobile)){
		        		buttomLine+=lineSpace;
		        		over.showTextAligned(Element.ALIGN_LEFT, mobile_title, 17.5f, buttomLine, 0);
		        		over.showTextAligned(Element.ALIGN_LEFT, DELIMITER, 43f, buttomLine, 0);
		        		over.showTextAligned(Element.ALIGN_LEFT, mobile, 49f, buttomLine, 0);
	        		}
	        		if(StringUtils.isNotBlank(officeFax)){
		        		buttomLine+=lineSpace;
		        		over.showTextAligned(Element.ALIGN_LEFT, fax_title, 17.5f, buttomLine, 0);
		        		over.showTextAligned(Element.ALIGN_LEFT, DELIMITER, 43f, buttomLine, 0);
		        		over.showTextAligned(Element.ALIGN_LEFT, officeFax, 49f, buttomLine, 0);
	        		}
	        		if(StringUtils.isNotBlank(officeDirect)){
		        		buttomLine+=lineSpace;
		        		over.showTextAligned(Element.ALIGN_LEFT, tel_title, 17.5f, buttomLine, 0);
		        		over.showTextAligned(Element.ALIGN_LEFT, DELIMITER, 43f, buttomLine, 0);
		        		over.showTextAligned(Element.ALIGN_LEFT, officeDirect, 49f, buttomLine, 0);
	        		}
	        		if(StringUtils.isNotBlank(officeAddr2)){
		        		buttomLine+=lineSpace;
		        		over.showTextAligned(Element.ALIGN_LEFT, officeAddr2, 17.5f, buttomLine, 0);
	        		}
	        		buttomLine+=lineSpace;
	        		over.showTextAligned(Element.ALIGN_LEFT, officeAddr, 17.5f, buttomLine, 0);
	        		buttomLine+=lineSpace;
	        		over.showTextAligned(Element.ALIGN_LEFT, officeName, 17.5f, buttomLine, 0);
	        		buttomLine+=lineSpace;
	        		over.setFontAndSize(fontBold, 12);
	        		over.showTextAligned(Element.ALIGN_LEFT, companyName, 17.5f, buttomLine, 0);
	        		over.endText();
	        	}
	        	
        		if(isDone) break;
        		if("".equals(member.getMmbFnameEn())) break;
        		if(company!=null){
        			companyName = company.getCompanyNameEn();
        		}
        		//English
        		if(member!=null){
	            	name = String.format("%s %s",member.getMmbFnameEn(), member.getMmbLnameEn());
	            	position = member.getMmbPositionEn();
	            	dept = member.getMmbDeptEn();
        		}

        		officeName = "";
        		officeAddr = "";
        		officeAddr2 = "";

        		mobile_title = "";
        		tel_title = "";
        		fax_title = "";
        		
        		if(member!=null){
        			if(StringUtils.isNotBlank(member.getMmbOfficeNameEn())){
        				officeName = member.getMmbOfficeNameEn();
        			}
        			if(StringUtils.isNotBlank(member.getMmbOfficeAddrEn())){
        				officeAddr = member.getMmbOfficeAddrEn();
        			}
	    			if(StringUtils.isNotBlank(member.getMmbOfficeAddr2En())){
	    				officeAddr2 = member.getMmbOfficeAddr2En();
	    			}
	    			agentCodeTitle = AGENT_CODE_TITLE_EN;
        			mobile_title = MOBILE_TITLE_EN;
        			tel_title = TELEPHONE_TITLE_SALE_EN;
        			fax_title = FAX_TITLE_EN;
        		}
        		currentPageLanguage=PRINT_TYPE_FLAG[PRINT_TYPE_FLAG_DEF_IDX+1];
        		isDone = true;
        		document.newPage();
	        }while(true);
	        document.close();
		}catch(Exception ex){
			logger.error(ex.getStackTrace());
			ex.printStackTrace();
		}finally{
			if(writer!=null) try{ writer.close(); }catch(Exception ex){ logger.error("writer.close() fail."); }
		}
		
		if(logger.isDebugEnabled()){
			logger.debug("fullPDFPathFile::" + fullPDFPathFile);
			logger.debug("PDF (java.io.File)output::" + output);
		}
	}
}